<template>
  <div class="comparison-container">
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <h3>智能比价系统</h3>
          <el-button type="primary" @click="generateReport">生成报告</el-button>
        </div>
      </template>
      
      <el-form :model="filterForm" label-width="100px" :inline="true">
        <el-form-item label="物料类别">
          <el-select v-model="filterForm.category" placeholder="请选择物料类别" clearable>
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="采购金额">
          <el-select v-model="filterForm.amountRange" placeholder="采购金额范围" clearable>
            <el-option label="0-10万" value="0-100000" />
            <el-option label="10-50万" value="100000-500000" />
            <el-option label="50-100万" value="500000-1000000" />
            <el-option label="100万以上" value="1000000-" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="供应商等级">
          <el-select v-model="filterForm.supplierLevel" placeholder="供应商等级" multiple collapse-tags>
            <el-option label="A级" value="A" />
            <el-option label="B级" value="B" />
            <el-option label="C级" value="C" />
            <el-option label="D级" value="D" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="采购时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 比价结果区域 -->
    <div class="comparison-content">
     
       <!-- 左侧图表分析 -->
      <div class="chart-area">
        <price-comparison-chart 
          v-model:chartType="chartType"
          :table-data="tableData"
          :suppliers="suppliers"
          @chart-ready="handleChartReady"
        />
        
        <price-trend-chart 
          v-model:selectedMaterial="selectedMaterial"
          :suppliers="suppliers"
          @chart-ready="handleChartReady"
        />
        
        <div v-if="!allChartsReady" class="charts-loading-overlay">
          <el-icon class="is-loading"><loading /></el-icon>
          <p>图表加载中...</p>
            </div>
      </div>
      <!-- 右侧比价表格 -->
      <div class="table-area">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>供应商报价明细</span>
              <div>
                <el-tooltip content="导出Excel" placement="top">
                  <el-button type="primary" icon="el-icon-download" circle size="small" @click="exportToExcel"></el-button>
                </el-tooltip>
                <el-tooltip content="刷新数据" placement="top">
                  <el-button icon="el-icon-refresh" circle size="small" @click="refreshData"></el-button>
                </el-tooltip>
              </div>
            </div>
          </template>
          
          <el-table
            v-loading="loading"
            :data="tableData"
            border
            stripe
            style="width: 100%"
            :header-cell-style="{background:'#f5f7fa'}"
          >
            <el-table-column prop="materialCode" label="物料编码" width="120" />
            <el-table-column prop="materialName" label="物料名称" width="150" />
            <el-table-column prop="specification" label="规格型号" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="quantity" label="采购数量" width="100" />
            
            <el-table-column label="供应商报价信息">
              <el-table-column v-for="(supplier, index) in suppliers" :key="supplier.id" :label="supplier.name">
                <el-table-column :label="`单价(元)`" :prop="`suppliers[${index}].price`" width="100">
                  <template #default="scope">
                    <span :class="{ 'lowest-price': isLowestPrice(scope.row, supplier.id) }">
                      {{ formatPrice(scope.row.suppliers[index]?.price) }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column :label="`总价(元)`" width="120">
                  <template #default="scope">
                    {{ calculateTotalPrice(scope.row.suppliers[index]?.price, scope.row.quantity) }}
                  </template>
                </el-table-column>
                <el-table-column :label="`交期(天)`" :prop="`suppliers[${index}].deliveryDays`" width="90" />
                <el-table-column :label="`评分`" width="80">
                  <template #default="scope">
                    <el-rate
                      v-model="scope.row.suppliers[index].rating"
                      disabled
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                    />
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table-column>
            
            <el-table-column label="推荐供应商" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.recommendation" type="success">
                  {{ scope.row.recommendation }}
                </el-tag>
                <el-button v-else link @click="generateRecommendation(scope.row)">
                  生成推荐
                </el-button>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button link size="small" @click="viewDetail(scope.row)">查看详情</el-button>
                <el-button link size="small" @click="compareSuppliers(scope.row)">比较分析</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
        
        <!-- 智能分析建议 -->
        <el-card class="analysis-card">
          <template #header>
            <div class="card-header">
              <span>智能分析建议</span>
              <el-switch v-model="showAnalysis" active-text="展示分析" inactive-text="隐藏分析" />
            </div>
          </template>
          
          <div v-if="showAnalysis" class="analysis-content">
            <el-collapse v-model="activeCollapse">
              <el-collapse-item title="总体比价分析" name="1">
                <div class="analysis-item">
                  <p><strong>采购总金额对比：</strong> 从当前选择的物料来看，供应商A的总体报价最优，比平均价格低12.5%。</p>
                  <p><strong>交货周期：</strong> 供应商C的平均交货周期最短，为8.3天，但价格略高。</p>
                  <p><strong>历史合作：</strong> 供应商B的历史履约率最高，达到98.7%，质量稳定性好。</p>
                </div>
              </el-collapse-item>
              
              <el-collapse-item title="价格波动分析" name="2">
                <div class="analysis-item">
                  <p><strong>市场行情：</strong> 本季度原材料价格上涨5.3%，但供应商A报价仅上涨2.1%，具有较好的成本控制能力。</p>
                  <p><strong>预测趋势：</strong> 根据历史数据分析，预计下季度价格将趋于稳定，建议适当囤货。</p>
                </div>
              </el-collapse-item>
              
              <el-collapse-item title="供应商评估" name="3">
                <div class="analysis-item">
                  <p><strong>综合得分：</strong></p>
                  <el-progress :percentage="88" :format="format" status="success">供应商A</el-progress>
                  <el-progress :percentage="76" :format="format">供应商B</el-progress>
                  <el-progress :percentage="82" :format="format" status="warning">供应商C</el-progress>
                  <p><strong>建议：</strong> 综合考虑价格、质量和交期，建议选择供应商A作为主要供应商，供应商C作为备选。</p>
                </div>
              </el-collapse-item>
              
              <el-collapse-item title="节约潜力分析" name="4">
                <div class="analysis-item">
                  <p><strong>议价空间：</strong> 通过历史数据分析，供应商A在大批量采购时有5-8%的降价空间。</p>
                  <p><strong>优化建议：</strong> 建议与供应商A签订长期框架协议，预计可节约采购成本约13.7万元/年。</p>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 详情抽屉 -->
    <el-drawer
      title="供应商详细对比"
      v-model="drawerVisible"
      direction="rtl"
      size="60%"
    >
      <div class="drawer-content">
        <el-descriptions :title="`物料：${currentMaterial?.materialName || ''}`" :column="1" border>
          <el-descriptions-item label="物料编码">{{ currentMaterial?.materialCode }}</el-descriptions-item>
          <el-descriptions-item label="规格型号">{{ currentMaterial?.specification }}</el-descriptions-item>
          <el-descriptions-item label="采购数量">{{ currentMaterial?.quantity }} {{ currentMaterial?.unit }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="center">供应商详细对比</el-divider>
        
        <el-table :data="supplierComparisonData" border stripe style="width: 100%">
          <el-table-column prop="item" label="对比项" width="150" />
          <el-table-column v-for="supplier in suppliers" :key="supplier.id" :label="supplier.name" />
        </el-table>
        
        <el-divider content-position="center">历史采购记录</el-divider>
        
        <el-table :data="historyRecords" border stripe style="width: 100%">
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="supplier" label="供应商" width="150" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="price" label="单价(元)" width="120" />
          <el-table-column prop="totalPrice" label="总价(元)" width="150" />
          <el-table-column prop="deliveryDays" label="实际交期(天)" width="120" />
          <el-table-column prop="qualityRating" label="质量评分">
            <template #default="scope">
              <el-rate v-model="scope.row.qualityRating" disabled />
            </template>
          </el-table-column>
        </el-table>
        
        <el-divider content-position="center">智能决策支持</el-divider>
        
        <el-card class="decision-card">
          <div class="decision-content">
            <h4>综合建议</h4>
            <p>基于价格、质量、交期和历史合作情况的综合评分，系统推荐选择<strong>供应商A</strong>。</p>
            <h4>决策依据</h4>
            <ul>
              <li>供应商A价格竞争力较强，比平均市场价低8.5%</li>
              <li>过去一年合作项目中，供应商A的交期达成率为97.3%</li>
              <li>质量问题处理响应速度快，平均处理时间为1.2天</li>
              <li>供应商财务稳定性良好，经营风险评级为低风险</li>
            </ul>
          </div>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import PriceComparisonChart from '../../../components/charts/PriceComparisonChart.vue'
import PriceTrendChart from '../../../components/charts/PriceTrendChart.vue'
import { Loading } from '@element-plus/icons-vue'

// 定义类型
interface Supplier {
  id: string;
  name: string;
  level: string;
}

interface SupplierData {
  price?: number;
  deliveryDays?: number;
  rating?: number;
}

interface MaterialItem {
  materialCode: string;
  materialName: string;
  specification: string;
  unit: string;
  quantity: number;
  suppliers: SupplierData[];
  recommendation: string;
}

interface FilterForm {
  category: string;
  amountRange: string;
  supplierLevel: string[];
  dateRange: any[];
}

// 图表实例
let priceComparisonChart: any = null
let priceTrendChart: any = null

// 加载状态
const loading = ref(false)
const chartType = ref('bar')
const showAnalysis = ref(true)
const activeCollapse = ref(['1'])
const drawerVisible = ref(false)
const currentMaterial = ref<MaterialItem | null>(null)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 物料和供应商选择
const selectedMaterial = ref('')

// 筛选表单
const filterForm = reactive<FilterForm>({
  category: '',
  amountRange: '',
  supplierLevel: [],
  dateRange: []
})

// 下拉选项数据
const categoryOptions = [
  { value: 'rawMaterial', label: '原材料' },
  { value: 'components', label: '零部件' },
  { value: 'equipment', label: '设备' },
  { value: 'officeSupplies', label: '办公用品' },
  { value: 'packaging', label: '包装材料' }
]

const materialOptions = [
  { value: 'M001', label: '钢板Q235' },
  { value: 'M002', label: '铝合金板6061' },
  { value: 'M003', label: '紫铜棒T2' },
  { value: 'M004', label: '橡胶垫片' },
  { value: 'M005', label: '轴承SKF6204' }
]

// 供应商数据
const suppliers = [
  { id: 'S001', name: '供应商A', level: 'A' },
  { id: 'S002', name: '供应商B', level: 'B' },
  { id: 'S003', name: '供应商C', level: 'A' }
]

// 表格数据
const tableData = ref([
  {
    materialCode: 'M001',
    materialName: '钢板Q235',
    specification: '1.2mm×1220mm×2440mm',
    unit: '张',
    quantity: 50,
    suppliers: [
      { price: 320, deliveryDays: 7, rating: 4.5 },
      { price: 350, deliveryDays: 5, rating: 4 },
      { price: 335, deliveryDays: 6, rating: 4.2 }
    ],
    recommendation: '供应商A'
  },
  {
    materialCode: 'M002',
    materialName: '铝合金板6061',
    specification: '2mm×1220mm×2440mm',
    unit: '张',
    quantity: 30,
    suppliers: [
      { price: 580, deliveryDays: 10, rating: 4.2 },
      { price: 560, deliveryDays: 12, rating: 4.5 },
      { price: 590, deliveryDays: 8, rating: 3.8 }
    ],
    recommendation: '供应商B'
  },
  {
    materialCode: 'M003',
    materialName: '紫铜棒T2',
    specification: 'Φ20mm×1000mm',
    unit: '根',
    quantity: 100,
    suppliers: [
      { price: 280, deliveryDays: 8, rating: 4.3 },
      { price: 295, deliveryDays: 7, rating: 4.1 },
      { price: 275, deliveryDays: 10, rating: 4.0 }
    ],
    recommendation: '供应商C'
  },
  {
    materialCode: 'M004',
    materialName: '橡胶垫片',
    specification: '20×30×2mm',
    unit: '个',
    quantity: 1000,
    suppliers: [
      { price: 1.2, deliveryDays: 5, rating: 4.0 },
      { price: 1.1, deliveryDays: 6, rating: 3.8 },
      { price: 1.3, deliveryDays: 4, rating: 4.5 }
    ],
    recommendation: ''
  },
  {
    materialCode: 'M005',
    materialName: '轴承SKF6204',
    specification: '标准件',
    unit: '个',
    quantity: 200,
    suppliers: [
      { price: 45, deliveryDays: 7, rating: 4.8 },
      { price: 48, deliveryDays: 5, rating: 4.6 },
      { price: 43, deliveryDays: 10, rating: 4.4 }
    ],
    recommendation: '供应商C'
  }
])

// 供应商比较数据
const supplierComparisonData = ref([
  { 
    item: '报价(元)',
    'S001': '320.00',
    'S002': '350.00',
    'S003': '335.00'
  },
  {
    item: '交货周期(天)',
    'S001': '7',
    'S002': '5',
    'S003': '6'
  },
  {
    item: '付款条件',
    'S001': '月结30天',
    'S002': '月结45天',
    'S003': '月结30天'
  },
  {
    item: '质量等级',
    'S001': 'A级',
    'S002': 'A级',
    'S003': 'B级'
  },
  {
    item: '技术支持',
    'S001': '优',
    'S002': '良',
    'S003': '优'
  },
  {
    item: '售后服务响应',
    'S001': '24小时内',
    'S002': '48小时内',
    'S003': '24小时内'
  },
  {
    item: '财务风险',
    'S001': '低',
    'S002': '低',
    'S003': '中'
  }
])

// 历史采购记录
const historyRecords = ref([
  {
    date: '2023-03-15',
    supplier: '供应商A',
    quantity: 40,
    price: 330,
    totalPrice: 13200,
    deliveryDays: 8,
    qualityRating: 4.5
  },
  {
    date: '2023-02-10',
    supplier: '供应商C',
    quantity: 30,
    price: 340,
    totalPrice: 10200,
    deliveryDays: 7,
    qualityRating: 4.2
  },
  {
    date: '2022-12-05',
    supplier: '供应商B',
    quantity: 50,
    price: 320,
    totalPrice: 16000,
    deliveryDays: 6,
    qualityRating: 4.0
  }
])

// 格式化价格
const formatPrice = (price: number | undefined) => {
  if (price === undefined) return '-'
  return price.toFixed(2)
}

// 计算总价
const calculateTotalPrice = (price: number | undefined, quantity: number) => {
  if (price === undefined) return '-'
  return (price * quantity).toFixed(2)
}

// 判断是否最低价格
const isLowestPrice = (row: any, supplierId: string) => {
  if (!row.suppliers) return false
  
  const index = suppliers.findIndex(s => s.id === supplierId)
  if (index === -1) return false
  
  const currentPrice = row.suppliers[index]?.price
  if (currentPrice === undefined) return false
  
  for (let i = 0; i < row.suppliers.length; i++) {
    if (i !== index && row.suppliers[i]?.price !== undefined && row.suppliers[i].price < currentPrice) {
      return false
    }
  }
  
  return true
}

// 重置表单
const resetForm = () => {
  Object.keys(filterForm).forEach(key => {
    const k = key as keyof FilterForm;
    if (k === 'supplierLevel') {
      filterForm[k] = [];
    } else if (k === 'dateRange') {
      filterForm[k] = [];
    } else {
      // @ts-ignore - TS doesn't know we're handling all cases properly
      filterForm[k] = '';
    }
  })
}

// 处理查询
const handleSearch = () => {
  loading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询成功')
  }, 800)
}

// 生成报告
const generateReport = () => {
  ElMessageBox.confirm('确认生成比价分析报告?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    ElMessage({
      type: 'success',
      message: '报告已生成，请在消息中心查看'
    })
  }).catch(() => {})
}

// 生成推荐
const generateRecommendation = (row: MaterialItem) => {
  const index = tableData.value.findIndex(item => item.materialCode === row.materialCode)
  if (index !== -1) {
    // 模拟智能计算推荐供应商
    const randomSupplier = suppliers[Math.floor(Math.random() * suppliers.length)]
    tableData.value[index].recommendation = randomSupplier.name
    
    ElMessage({
      type: 'success',
      message: `已为${row.materialName}推荐最优供应商：${randomSupplier.name}`
    })
  }
}

// 查看详情
const viewDetail = (row: MaterialItem) => {
  currentMaterial.value = { ...row }
  drawerVisible.value = true
}

// 比较供应商
const compareSuppliers = (row: MaterialItem) => {
  currentMaterial.value = { ...row }
  drawerVisible.value = true
  
  // 在实际应用中，这里应该根据物料ID请求更详细的比较数据
}

// 导出到Excel
const exportToExcel = () => {
  ElMessage.success('数据已导出到Excel')
}

// 刷新数据
const refreshData = () => {
  loading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据已更新')
  }, 800)
}

// 处理页面大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  // 重新加载数据
  refreshData()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  // 重新加载数据
  refreshData()
}

// 进度条格式化
const format = (percentage: number) => {
  return percentage + '分'
}

// 图表就绪状态跟踪
const chartReadyStatus = reactive({
  priceComparisonChart: false,
  priceTrendChart: false
})

// 处理图表就绪事件
const handleChartReady = (chartId: string) => {
  chartReadyStatus[chartId as keyof typeof chartReadyStatus] = true
}

// 计算所有图表是否就绪
const allChartsReady = computed(() => {
  return chartReadyStatus.priceComparisonChart && chartReadyStatus.priceTrendChart
})

// 组件挂载时初始化
onMounted(() => {
  // 已由子组件处理图表初始化
})
  
// 组件卸载前清理资源
onBeforeUnmount(() => {
  // 已由子组件处理图表资源清理
})
</script>

<style scoped>
.comparison-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.comparison-content {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 20px;
}

.chart-area {
  flex: 1;
  min-width: 300px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: 400px;
  position: relative;
}

.table-area {
  flex: 1;
  min-width: 300px;
}

.chart-card {
  margin-bottom: 0;
  width: 100%;
}

.chart-container {
  height: 350px;
  width: 100%;
  position: relative;
  display: block;
}

.analysis-card {
  margin-top: 20px;
}

.analysis-content {
  padding: 10px;
}

.analysis-item {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.lowest-price {
  color: #67C23A;
  font-weight: bold;
}

.drawer-content {
  padding: 20px;
}

.decision-card {
  margin-top: 20px;
}

.decision-content {
  padding: 10px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .comparison-content {
    flex-direction: column;
  }
  
  .chart-container {
    height: 300px;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .comparison-container {
    padding: 10px;
  }
  
  .comparison-content {
    gap: 10px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .card-header > div, .card-header > span {
    margin-bottom: 8px;
  }
  
  .el-form {
    display: flex;
    flex-direction: column;
  }
  
  .el-form-item {
    width: 100%;
    margin-right: 0;
  }
  
  .el-select, .el-date-picker {
    width: 100% !important;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .analysis-content {
    padding: 5px;
  }
  
  .drawer-content {
    padding: 10px;
  }
}

/* 小屏幕手机适配 */
@media (max-width: 480px) {
  .comparison-container {
    padding: 5px;
  }
  
  .chart-container {
    height: 200px;
  }
  
  .el-pagination {
    font-size: 12px;
  }
  
  .el-button {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  .el-table {
    font-size: 11px;
  }
  
  .el-table th, .el-table td {
    padding: 6px 0;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .filter-card,
  .chart-card,
  .analysis-card,
  .decision-card {
    background-color: var(--el-bg-color-overlay, #1d1e1f);
    color: var(--el-text-color-primary, #e5eaf3);
  }
}

/* 打印样式优化 */
@media print {
  .comparison-container {
    padding: 0;
  }
  
  .chart-container {
    page-break-inside: avoid;
  }
  
  .el-button {
    display: none;
  }
}

.charts-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.charts-loading-overlay .el-icon {
  font-size: 32px;
  margin-bottom: 10px;
  color: var(--el-color-primary);
}
</style>